package com.example.config;

import cn.hutool.core.thread.NamedThreadFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;

import java.util.concurrent.*;

/**
 * 自定义异步配置
 * @author long
 * @date 2024/8/21 20:18
 */
@Configuration
public class CustomAsyncConfigurer implements AsyncConfigurer {

    /**
     * 创建一个线程池
     * @return
     */
    @Bean("custom-executor")
    public Executor createExecutor(){
        ThreadFactory threadFactory = new NamedThreadFactory("自定义线程池",false);
        return new ThreadPoolExecutor(5,5,60,
                TimeUnit.SECONDS,new ArrayBlockingQueue<>(100),threadFactory,new ThreadPoolExecutor.CallerRunsPolicy());
    }

    @Override
    public Executor getAsyncExecutor() {
        ThreadFactory threadFactory = new NamedThreadFactory("实现AsyncConfigurer",false);
        return new ThreadPoolExecutor(5,5,60,
                TimeUnit.SECONDS,new ArrayBlockingQueue<>(100),threadFactory,new ThreadPoolExecutor.CallerRunsPolicy());
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }

}
